<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/11/13 0013
 * Time: 下午 3:35
 */
namespace Admin\Controller;
class LeagueController extends CommonController
{
    public function _initialize()
    {
        parent::_initialize();
        $this->_mod = D('User');
        $this->_cate_mod = D('UserCate');
    }
    public function _before_index()
    {
        $this->options = $this->check();
        $p = I('p', 1, 'intval');
        $this->assign('p', $p);
    }

    public function index()
    {
        $page = I('get.p', 1, 'int');
        $obj = D("User as u");
        $fex = C('DB_PREFIX');
        $map = $this->_search(3);
        $pagesize = 20;
        $count = $obj->join('left join ' . $fex . 'user_info as uf on u.id = uf.user_id')
            ->join('left join ' . $fex . 'user_cate as uc on uf.cate_id = uc.id')
            ->where($map)->count();
        $pageObj = new \Org\Yike\Page($count, $pagesize);
        $lists = $obj->join('left join ' . $fex . 'user_info as uf on u.id = uf.user_id')
            ->join('left join ' . $fex . 'user_cate as uc on uf.cate_id = uc.id')
            ->join('left join ' . $fex . 'user_account as ac on ac.user_id = u.id')
            ->field('u.*,uf.reg_time,uf.head_ico,uf.id_type,uc.name,ac.blance,ac.point,ac.freeze')
            ->where($map)
            ->order('uf.reg_time desc')
            ->page($page, $pageObj->listRows)
            ->select();
        $this->assign('list', $lists);
        $this->assign('page', $pageObj->show());
        $this->display();
    }

    protected function _search($cate_id)
    {
        $map = array();
        ($keyword = I('get.keyword')) && $map['u.username|u.email'] = array('like', '%' . $keyword . '%');
        $cate_id = $cate_id;
        if ($_GET['status'] == null) {
            $status = -1;
        } else {
            $status = intval($_GET['status']);
        }
        $status >= 0 && $map['u.status'] = array('eq', $status);
        $selected_ids = '';
        if ($cate_id) {
            $id_arr = $this->_cate_mod->get_child_ids($cate_id, true);
            $map['uf.cate_id'] = array('IN', $id_arr);
            $spid = $this->_cate_mod->where(array('id' => $cate_id))->getField('spid');
            $selected_ids = $spid ? $spid . $cate_id : $cate_id;
        }

        $this->assign('search', array(
            'cate_id' => $cate_id,
            'selected_ids' => $selected_ids,
            'status' => $status,
            'keyword' => $keyword,
        ));
        return $map;
    }
    //修改密码
    public function pass(){
        if($_POST){
            $password = trim($_POST['password']);
            $data['password']  = _md5($password);
            $res = M('user')->where(array('id'=>intval($_POST['id'])))->save($data);
            if($res){
                $this->success('修改密码成功');
            }else{
                $this->error('修改密码失败');
            }
        }else{
            $this->info = M('user')->where(array('id'=>intval($_GET['id'])))->find();
            $this->display();
        }
    }
    //审核信息
    public function examine(){
        if($_POST){
            $uid = I ('post.uid','');
            $str = I ('post.str','');
            if ($str == 'pass') $status = 1;
            if ($str == 'notpass') $status = -1;
            $userMOD = D ('user');
            $res = $userMOD->where ( array ('id'=>$uid))->setField (array ('status'=>$status));
            if ($res !== false){
                exit (json_encode( array ('state'=>1,'msg'=>'审核完成')));
            } else{
                exit (json_encode( array ('state'=>-1,'msg'=>'网络错误')));
            }
        } else{
            $id = I('get.id');
            $user = M("user")->where(array('id'=>$id))->find();
            $userInfo = M("UserInfo")->where(array('user_id'=>$id))->find();
            $spid = $this->_cate_mod->where(array('id'=>$userInfo['cate_id']))->getField('spid');
            $account = M("UserAccount")->where(array('user_id'=>$id))->find();
            if( $spid==0 ){
                $spid = $userInfo['cate_id'];
            }else{
                $spid .= $userInfo['cate_id'];
            }
            $this->assign('user',$user);
            $this->assign('data',unserialize($userInfo['data']));
            $this->assign('userInfo',$userInfo);
            $this->assign('selected_ids',$spid);
            $this->assign('account',$account);
            $conf = getUserInfoConf();
            $this->assign ('id_type', $conf['id_type'][$userInfo['id_type']]);
            $this->display();
        }

    }

    //成功返回
    protected function _after_insert($id){
        $info = $_POST['info'];
        $info['user_id'] = $id;
        $info['reg_time'] = $info['login_time'] = time();
        $info['reg_ip']   = $info['login_ip']   = get_client_ip();
        $obj = D("UserInfo");
        $obj->create($info);
        if($obj->add()){
            D("UserAccount")->add(array('user_id'=>$id));
        }
    }
    public function checkusername(){
        $username = I('get.username','');
        $email    = I('get.email','');
        if($username){
            $map['username'] = array('eq',$username);
        }
        if($email){
            $map['email'] = array('eq',$email);
        }
        $info = D("User")->where($map)->find();
        if($info){
            $this->ajaxReturn(0);
        }else{
            $this->ajaxReturn(1);
        }
    }

    public function _after_delete($ids){
        $map['user_id'] = array('in',$ids);
        D("UserInfo")->where($map)->delete();
        D("UserAccount")->where($map)->delete();
        D("UserRecord")->where($map)->delete();
    }

    public function edit(){
        $id = I('get.id');
        $user = M("user")->where(array('id'=>$id))->find();
        $userInfo = M("UserInfo")->where(array('user_id'=>$id))->find();
        $spid = $this->_cate_mod->where(array('id'=>$userInfo['cate_id']))->getField('spid');
        $account = M("UserAccount")->where(array('user_id'=>$id))->find();
        //店铺列表
        $shops = M ('shop')->select ();
        if( $spid==0 ){
            $spid = $userInfo['cate_id'];
        }else{
            $spid .= $userInfo['cate_id'];
        }
        $this->assign('user',$user);
        $this->assign('data',unserialize($userInfo['data']));
        $this->assign('userInfo',$userInfo);
        $this->assign('selected_ids',$spid);
        $this->assign('account',$account);
        $this->assign('shops',$shops);
        $this->conf = getUserInfoConf();
        $this->display();
    }


    //更新成功返回
    protected function _after_update($id){
        $info = $_POST['info'];
        $obj = D("UserInfo");
        $obj->where(array('user_id'=>$id))->save($info);
        $account = $_POST['account'];
        if(!empty($account['point'])){
            switch($account['pointtype']){
                case 'setinc':
                    $record['num'] = $account['point'];
                    $record['title'] = '管理员增加积分'.$account['point'];
                    break;
                case 'setdesc':
                    $record['num'] = -1*$account['point'];
                    $record['title'] = '管理员减少积分'.$account['point'];
                    break;
            }
            $record['memo'] = '管理员操作';
            Record($id,$record);
        }
        if(!empty($account['money'])){
            switch($account['moneytype']){
                case 'setinc':
                    $record['num'] = $account['money'];
                    $record['title'] = '管理员增加余额'.$account['money'];
                    break;
                case 'setdesc':
                    $record['num'] = -1*$account['money'];
                    $record['title'] = '管理员减少余额'.$account['money'];
                    break;
                case 'freeze':
                    $useraccount = $this->getUserBlance($id);
                    if($useraccount['blance']<$account['money']){
                        $this->error('可冻结余额最多为：'.$useraccount['blance']);
                    }
                    $record['num'] = -1*$account['money'];
                    $record['title'] = '管理员冻结余额'.$account['money'];
                    D("UserAccount")->where(array('uid'=>$id))->setInc('freeze',abs($record['num']));
                    break;
                case 'unfreeze':
                    $useraccount = $this->getUserBlance($id);
                    if($useraccount['freeze']<$account['money']){
                        $this->error('可解冻余额最多为：'.$useraccount['freeze']);
                    }
                    $record['num'] = $account['money'];
                    $record['title'] = '管理员解冻余额'.$account['money'];
                    D("UserAccount")->where(array('uid'=>$id))->setDec('freeze',abs($record['num']));
                    break;
            }
            $record['memo'] = '管理员操作';
            Record($id,$record,2);
        }
    }

    //用户认证
    public function identity(){
        if($_POST['id']){
            $data = array(
                'is_auth'=>intval($_POST['is_auth'])
            );
            $res = M('UserInfo')->where(array('id'=>$_POST['id']))->save($data);
            if($res){
                $this->success(L('operation_success'));
            }else{
                $this->error(L('operation_failure'));
            }
        }else{
            $info= M('UserInfo')->where(array('user_id'=>intval($_GET['id'])))->find();
            $info['username'] = M('user')->where(array('id'=>$info['user_id']))->getField('username');
            $this->info=$info;
            $this->display();
        }
    }

    //用户头像审核
    public function pic(){
        if($_POST['id']){
            $info = M('UserInfo')->where(array('id'=>$_POST['id']))->find();
            if(!$info['head_icotemp']){
                $this->error('没有需要审核的头像!');
            }
            $data = array(
                'head_ico'=>$info['head_icotemp'],
                'head_status'=>1,
                'head_icotemp'=>''
            );
            $res = M('UserInfo')->where(array('id'=>$_POST['id']))->save($data);
            if($res){
                $this->success(L('operation_success'));
            }else{
                $this->error(L('operation_failure'));
            }
        }else{
            $this->info= M('UserInfo')->where(array('user_id'=>intval($_GET['id'])))->find();
            $this->display();
        }
    }

    private function getUserBlance($id){
        $map['user_id'] = $id;
        $userAccount = D("UserAccount")->where(array('user_id'=>$id))->find();
        return $userAccount;
    }

    //更新配置文件
    public function setting(){
        $file = APP_PATH.'/Member/Conf/user.php';
        if(!is_file($file)){
            fopen($file,'a');
        }
        if(IS_POST){
            $url = d_name('hw').'/user.php?m=Member&c=Login&a=callback&type=';
            $data = array(
                'ALLOW_REGSITER' => I('post.can_reg',1,'int'),
                'REGSITER_POINT' => I('post.give_point',0,'int'),
                'REGSITER_MONEY' => I('post.give_money',0,'int'),
                'LOGIN_POINT'    => I('post.login_point',0,'int'),
                'RENTAL_STATUS' => I('post.rental_status',0,'int'),
                'USED_STATUS' => I('post.used_status',0,'int'),
                'ARTICLE_STATUS' => I('post.article_status',0,'int'),
                'ASK_STATUS' => I('post.ask_status',0,'int'),

                'THINK_SDK_QQ' => array(
                    'APP_KEY'  => $_POST['qq']['appkey'],
                    'APP_SECRET' => $_POST['qq']['appsecret'],
                    'CALLBACK'   => $url.'qq',
                ),

                'THINK_SDK_TAOBAO' => array(
                    'APP_KEY' => $_POST['tb']['appkey'], //应用注册成功后分配的 APP ID
                    'APP_SECRET' => $_POST['tb']['appsecret'], //应用注册成功后分配的KEY
                    'CALLBACK' => $url . 'taobao',
                ),
                'THINK_SDK_SINA' => array(
                    'APP_KEY' => $_POST['sina']['appkey'], //应用注册成功后分配的 APP ID
                    'APP_SECRET' => $_POST['sina']['appsecret'], //应用注册成功后分配的KEY
                    'CALLBACK' => $url . 'sina',
                ),
            );
            if(update_config($data,$file)){
                $this->success('更新成功');
            }else{
                $this->error('更新失败');
            }
        }else{

            $config = require($file);
            $con['can_reg'] = $config['ALLOW_REGSITER'];
            $con['reg_point'] = $config['REGSITER_POINT'];
            $con['reg_money'] = $config['REGSITER_MONEY'];
            $con['login_point'] = $config['LOGIN_POINT'];
            $con['used_status'] = $config['USED_STATUS'];
            $con['rental_status'] = $config['RENTAL_STATUS'];
            $con['article_status'] = $config['ARTICLE_STATUS'];
            $con['ask_status'] = $config['ASK_STATUS'];
            $con['qq']['appkey'] = $config['THINK_SDK_QQ']['APP_KEY'];
            $con['qq']['appsecret'] = $config['THINK_SDK_QQ']['APP_SECRET'];
            $con['tb']['appkey'] = $config['THINK_SDK_TAOBAO']['APP_KEY'];
            $con['tb']['appsecret'] = $config['THINK_SDK_TAOBAO']['APP_SECRET'];
            $con['sina']['appkey'] = $config['THINK_SDK_SINA']['APP_KEY'];
            $con['sina']['appsecret'] = $config['THINK_SDK_SINA']['APP_SECRET'];
            $this->assign('config',$con);
            $this->display();
        }
    }

    public function publicSelect(){
        $this->type = I('get.type') ? I('get.type') : 'radio';
        $where = array('status'=>1);
        $this->result = $this->_mod->where($where)->order('id desc')->field('id,username')->limit(24)->select();
        $count   = $this->_mod->where($where)->count();
        $pageObj = new \Org\Util\Page($count,24);
        $this->pages=$pageObj->ajaxPage(1);
        $response = $this->fetch('selectUser');
        $this->ajaxReturn(1,'',$response);
    }

    public function ajaxSelectUser(){
        $pagesize = 24;
        $q      = I('get.q');
        $page   = I('get.page',1,'int');
        $where  = array();

        if($q){
            $where['username|email'] = array('like','%'.$q.'%');
        }
        // $productObj = M('product');
        //分页类
        $count   = $this->_mod->where($where)->count();
        $pageObj = new \Org\Util\Page($count,$pagesize);
        $result = $this->_mod->where($where)->field('id,username')->order('id desc')->page($page,$pageObj->listRows)->select();
        $res    = array('page'=>$pageObj->ajaxPage($page),'data'=>$result);
        $this->ajaxReturn(1,'',$res);
    }
}